//
//  EWRegisterViewController.m
//  haveSomethingToEat
//
//  Created by 陈 宁权 on 17/4/24.
//  Copyright © 2017年 陈 宁权. All rights reserved.
//

#import "EWRegisterViewController.h"
#import "EWTextField.h"
#import "EWTabBarController.h"

@interface EWRegisterViewController ()

@property (nonatomic,strong) UITextField *userId;
@property (nonatomic,strong) UITextField *userName;
@property (nonatomic,strong) UITextField *password;
@property (nonatomic,strong) UITextField *confirmPwd;
@property (nonatomic,strong) UITextField *VFCode;
@property (nonatomic,strong) EWTextField *mobile;
@property (nonatomic,strong) UIButton *getVerificationBtn;
@property (nonatomic,strong) NSTimer *countDownTimer;

@end

static NSInteger secondsCountDown = 60;

@implementation EWRegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view setBackgroundColor:[UIColor whiteColor]];
    //配置导航栏
    [self configNav];
    //设置子视图
    [self setUpChildView];
}

- (void)configNav
{
    [self.navigationItem setTitle:@"新用户注册"];
    
    UIImageView *backView = [[UIImageView alloc] initWithImage:[[UIImage imageNamed:@"img_left_arrow"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]];
    backView.tintColor = [UIColor whiteColor];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(back)];
    [backView addGestureRecognizer:tap];
    
    UIButton *registBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    registBtn.frame = CGRectMake(0, 0, 60, 30);
    [registBtn setTitle:@"注册" forState:UIControlStateNormal];
    [registBtn addTarget:self action:@selector(regist) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *leftView = [[UIBarButtonItem alloc] initWithCustomView:backView];
    UIBarButtonItem *rightView = [[UIBarButtonItem alloc] initWithCustomView:registBtn];
    self.navigationItem.leftBarButtonItem = leftView;
    self.navigationItem.rightBarButtonItem = rightView;
}

- (void)setUpChildView
{
    UIView *lineView1 = [[UIView alloc] init];
    lineView1.backgroundColor = BASE_COLOR;
    [self.view addSubview:lineView1];
    
    UILabel *userIdLeftLabel = [[UILabel alloc] init];
    userIdLeftLabel.frame = CGRectMake(0, 0, 70, 30);
    userIdLeftLabel.font = [UIFont systemFontOfSize:13];
    userIdLeftLabel.textAlignment = NSTextAlignmentLeft;
    userIdLeftLabel.text = @"用户ID";
    
    _userId = [[UITextField alloc] init];
    _userId.placeholder = @"请输入用户ID(不大于11位)";
    _userId.font = [UIFont systemFontOfSize:13];
    _userId.borderStyle = UITextBorderStyleNone;
    _userId.leftView = userIdLeftLabel;
    _userId.leftViewMode = UITextFieldViewModeAlways;
    [self.view addSubview:_userId];
    
    UIView *lineView2 = [[UIView alloc] init];
    lineView2.backgroundColor = BASE_COLOR;
    [self.view addSubview:lineView2];
    
    UILabel *userNameLeftLabel = [[UILabel alloc] init];
    userNameLeftLabel.frame = CGRectMake(0, 0, 70, 30);
    userNameLeftLabel.font = [UIFont systemFontOfSize:13];
    userNameLeftLabel.textAlignment = NSTextAlignmentLeft;
    userNameLeftLabel.text = @"用户昵称";
    
    _userName = [[UITextField alloc] init];
    _userName.placeholder = @"请输入用户昵称(不大于30位)";
    _userName.font = [UIFont systemFontOfSize:13];
    _userName.borderStyle = UITextBorderStyleNone;
    _userName.leftView = userNameLeftLabel;
    _userName.leftViewMode = UITextFieldViewModeAlways;
    [self.view addSubview:_userName];
    
    UIView *lineView3 = [[UIView alloc] init];
    lineView3.backgroundColor = BASE_COLOR;
    [self.view addSubview:lineView3];
    
    UILabel *passwordLeftLabel = [[UILabel alloc] init];
    passwordLeftLabel.frame = CGRectMake(0, 0, 70, 30);
    passwordLeftLabel.font = [UIFont systemFontOfSize:13];
    passwordLeftLabel.textAlignment = NSTextAlignmentLeft;
    passwordLeftLabel.text = @"密码";
    
    _password = [[UITextField alloc] init];
    _password.placeholder = @"请输入密码(6-11位)";
    _password.font = [UIFont systemFontOfSize:13];
    _password.borderStyle = UITextBorderStyleNone;
    _password.secureTextEntry = YES;
    _password.leftView = passwordLeftLabel;
    _password.leftViewMode = UITextFieldViewModeAlways;
    [self.view addSubview:_password];
    
    UIView *lineView4 = [[UIView alloc] init];
    lineView4.backgroundColor = BASE_COLOR;
    [self.view addSubview:lineView4];
    
    UILabel *confirmPwdLeftLabel = [[UILabel alloc] init];
    confirmPwdLeftLabel.frame = CGRectMake(0, 0, 70, 30);
    confirmPwdLeftLabel.font = [UIFont systemFontOfSize:13];
    confirmPwdLeftLabel.textAlignment = NSTextAlignmentLeft;
    confirmPwdLeftLabel.text = @"确认密码";
    
    _confirmPwd = [[UITextField alloc] init];
    _confirmPwd.placeholder = @"请再次输入密码";
    _confirmPwd.font = [UIFont systemFontOfSize:13];
    _confirmPwd.borderStyle = UITextBorderStyleNone;
    _confirmPwd.secureTextEntry = YES;
    _confirmPwd.leftView = confirmPwdLeftLabel;
    _confirmPwd.leftViewMode = UITextFieldViewModeAlways;
    [self.view addSubview:_confirmPwd];
    
    UIView *lineView5 = [[UIView alloc] init];
    lineView5.backgroundColor = BASE_COLOR;
    [self.view addSubview:lineView5];
    
    UILabel *mobileLeftLabel = [[UILabel alloc] init];
    mobileLeftLabel.frame = CGRectMake(0, 0, 70, 30);
    mobileLeftLabel.font = [UIFont systemFontOfSize:13];
    mobileLeftLabel.textAlignment = NSTextAlignmentLeft;
    mobileLeftLabel.text = @"电话号码";
    
    _getVerificationBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_getVerificationBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    [_getVerificationBtn addTarget:self action:@selector(getCode) forControlEvents:UIControlEventTouchUpInside];
    _getVerificationBtn.backgroundColor = [UIColor colorWithRed:133/255.0 green:32/255.0 blue:133/255.0 alpha:1];
    _getVerificationBtn.titleLabel.textColor = [UIColor whiteColor];
    _getVerificationBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    _getVerificationBtn.layer.cornerRadius = 5;
    _getVerificationBtn.layer.masksToBounds = YES;
    _getVerificationBtn.frame = CGRectMake(0, 0, 80, 30);
    
    _mobile = [[EWTextField alloc] init];
    _mobile.placeholder = @"请输入电话号码";
    _mobile.font = [UIFont systemFontOfSize:13];
    _mobile.borderStyle = UITextBorderStyleNone;
    _mobile.leftView = mobileLeftLabel;
    _mobile.leftViewMode = UITextFieldViewModeAlways;
    _mobile.rightView = _getVerificationBtn;
    _mobile.rightViewMode = UITextFieldViewModeAlways;
    [self.view addSubview:_mobile];
    
    UIView *lineView6 = [[UIView alloc] init];
    lineView6.backgroundColor = BASE_COLOR;
    [self.view addSubview:lineView6];
    
    UILabel *VFCodeLeftLabel = [[UILabel alloc] init];
    VFCodeLeftLabel.frame = CGRectMake(0, 0, 70, 30);
    VFCodeLeftLabel.font = [UIFont systemFontOfSize:13];
    VFCodeLeftLabel.textAlignment = NSTextAlignmentLeft;
    VFCodeLeftLabel.text = @"验证码";
    
    _VFCode = [[UITextField alloc] init];
    _VFCode.placeholder = @"请输入验证码";
    _VFCode.font = [UIFont systemFontOfSize:13];
    _VFCode.borderStyle = UITextBorderStyleNone;
    _VFCode.leftView = VFCodeLeftLabel;
    _VFCode.leftViewMode = UITextFieldViewModeAlways;
    [self.view addSubview:_VFCode];
    
    UIView *lineView7 = [[UIView alloc] init];
    lineView7.backgroundColor = BASE_COLOR;
    [self.view addSubview:lineView7];
    
    [lineView1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(120);
        make.left.equalTo(self.view).offset(5);
        make.right.equalTo(self.view).offset(-5);
        make.height.offset(0.5);
    }];
    
    [_userId mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(lineView1.mas_bottom);
        make.left.equalTo(self.view).offset(20);
        make.right.equalTo(lineView1);
        make.height.offset(40);
    }];
    
    [lineView2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_userId.mas_bottom);
        make.left.equalTo(_userId.mas_left);
        make.right.equalTo(_userId.mas_right);
        make.height.offset(0.5);
    }];
    
    [_userName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(lineView2.mas_bottom);
        make.left.equalTo(self.view).offset(20);
        make.right.equalTo(lineView2);
        make.height.offset(40);
    }];
    
    [lineView3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_userName.mas_bottom);
        make.left.equalTo(_userName.mas_left);
        make.right.equalTo(_userName.mas_right);
        make.height.offset(0.5);
    }];
    
    [_password mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(lineView3.mas_bottom);
        make.left.equalTo(self.view).offset(20);
        make.right.equalTo(lineView3);
        make.height.offset(40);
    }];
    
    [lineView4 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_password.mas_bottom);
        make.left.equalTo(_password.mas_left);
        make.right.equalTo(_password.mas_right);
        make.height.offset(0.5);
    }];
    
    [_confirmPwd mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(lineView4.mas_bottom);
        make.left.equalTo(self.view).offset(20);
        make.right.equalTo(lineView4);
        make.height.offset(40);
    }];
    
    [lineView5 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_confirmPwd.mas_bottom);
        make.left.equalTo(_confirmPwd.mas_left);
        make.right.equalTo(_confirmPwd.mas_right);
        make.height.offset(0.5);
    }];
    
    [_mobile mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(lineView5.mas_bottom);
        make.left.equalTo(self.view).offset(20);
        make.right.equalTo(lineView5);
        make.height.offset(40);
    }];
    
    [lineView6 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_mobile.mas_bottom);
        make.left.equalTo(_mobile.mas_left);
        make.right.equalTo(_mobile.mas_right);
        make.height.offset(0.5);
    }];
    
    [_VFCode mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(lineView6.mas_bottom);
        make.left.equalTo(self.view).offset(20);
        make.right.equalTo(lineView6);
        make.height.offset(40);
    }];
    
    [lineView7 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_VFCode.mas_bottom);
        make.left.equalTo(self.view).offset(5);
        make.right.equalTo(self.view).offset(-5);
        make.height.offset(0.5);
    }];
}

- (void)getCode
{
    if ([self isMobileNumber:_mobile.text]) {
        [_mobile endEditing:YES];
        _mobile.enabled = NO;
        _countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDownAction) userInfo:nil repeats:YES];
        [_getVerificationBtn setTitle:[NSString stringWithFormat:@"已发送(%lds)",secondsCountDown] forState:UIControlStateNormal];
        _getVerificationBtn.backgroundColor = [UIColor grayColor];
        _getVerificationBtn.enabled = NO;
        
        //发送短信验证码
        [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS phoneNumber:_mobile.text zone:@"86" customIdentifier:nil result:^(NSError *error) {
            if (!error) {
                NSLog(@"验证码发送成功");
            }
            else
            {
                NSLog(@"error=%@",error);
            }
        }];
    }
    else
    {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的电话号码"];
    }
}

- (void)countDownAction
{
    secondsCountDown--;
    [_getVerificationBtn setTitle:[NSString stringWithFormat:@"已发送(%lds)",secondsCountDown] forState:UIControlStateNormal];
    if (secondsCountDown == 0) {
        [_countDownTimer invalidate];
        [_getVerificationBtn setTitle:@"发送验证码" forState:UIControlStateNormal];
        _getVerificationBtn.backgroundColor = [UIColor colorWithRed:133/255.0 green:32/255.0 blue:133/255.0 alpha:1];
        _getVerificationBtn.enabled = YES;
        _mobile.enabled = YES;
    }
}

//判断电话号码是否有效
- (BOOL)isMobileNumber:(NSString *)mobileNum
{
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

- (void)back
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)regist
{
    if (_password.text.length < 6 || _password.text.length > 11) {
        [SVProgressHUD showErrorWithStatus:@"请输入6-11位数的密码"];
    }
    if (![_password.text isEqualToString:_confirmPwd.text]) {
        [SVProgressHUD showErrorWithStatus:@"两次密码输入不一致，请重新输入"];
        return;
    }
    [SMSSDK commitVerificationCode:_VFCode.text phoneNumber:_mobile.text zone:@"86" result:^(SMSSDKUserInfo *userInfo, NSError *error) {
        
        if (!error) {
            [[BQUserDao shareObject] registerWithUserId:_userId.text andUserName:_userName.text andPassword:_password.text andMobile:_mobile.text andServiceReceiveResponseSuccess:^(id response) {
                
                //回到主线程跳转到登录页
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self dismissViewControllerAnimated:YES completion:nil];
                });
                
            } ServiceReceiveResponseFailed:^(id response) {
                [SVProgressHUD showErrorWithStatus:@"注册新用户失败"];
            }];
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:@"验证失败请输入正确的验证码"];
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
